package com.suxin.netty.buf;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.util.Random;

/**
 * @Classname ChannelClientHandler
 * @Description [ TODO ]
 * @Author Tang
 * @Date 2021/1/2 23:30
 * @Created by ASUS
 */
public class ChannelClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 通道就绪就会触发该方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        MyDataInfo.MyMessage myMessage = null;

        Random random = new Random();
        int nextInt = random.nextInt(3);
        if (nextInt == 1 || nextInt == 0) {
            myMessage = MyDataInfo.MyMessage.newBuilder()
                    .setDataType(MyDataInfo.MyMessage.DateType.studentType)
                    .setStudent(MyDataInfo.Student.newBuilder().setId(1).setName("tll").build())
                    .setDataTypeValue(0)
                    .build();
        } else {
            myMessage = MyDataInfo.MyMessage
                    .newBuilder().
                            setDataType(MyDataInfo.MyMessage.DateType.workerType)
                    .setWorker(MyDataInfo.Worker.newBuilder().setId(2).setName("worker"))
                    .setDataTypeValue(1)
                    .build();
        }
        ctx.writeAndFlush(myMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("服务器回复的消息：" + buf.toString(Charset.defaultCharset()));
        System.out.println("服务器的地址：" + ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}